<!DOCTYPE html>
<html>
    <title>
        聊天
    </title>
    <body>
        <h1>
            简易聊天
        </h1>
        <div id = "app">
            <input id="sendMsg" type="text" /> 
            <button id="submitbutton">发送</button>
        </div>
    </body>
   <script type="text/javascript">
    function showMessage(str,type) {
        var div = document.createElement("div");
        div.innerHTML = str;
        if(type == "enter"){
            div.style.color = "blue";
        } else if(type == "leave"){
            div.style.color = "red"
        }
        document.body.appendChild(div);
    }

    const ws = new WebSocket('ws://' + '116.205.185.181:8000' + '/ws/connection-test/');

    ws.onopen = function(){
        console.log("已连接websocket服务器");
        document.getElementById("submitbutton").onclick = function(){
            var txt = document.getElementById("sendMsg").value;
            if(txt){
                ws.send(txt);
                console.log("发送成功");
            }
        };
    };

    ws.onclose= function(){
        console.log("以断开websocket");
    };

    ws.onmessage = function(e){
        console.log("收到信息");
        var mes = JSON.parse(e.data);
        showMessage(mes.data,mes.type);
    };
   </script>
</html>